package com.nsgf.library.ui.page.video;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.VideoListBean;
import com.nsgf.library.databinding.ActivityNsgfHomeVideoBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.ClockInfoListAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 视频监控
 */
public class VideoListActivity extends BaseActivity {
    private CheckWorkAttendanceState mStates;

    private ClockInfoListAdapter mAdapter;
    ActivityNsgfHomeVideoBinding mBinding;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(CheckWorkAttendanceState.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new ClockInfoListAdapter(this);

        return new DataBindingConfig(R.layout.activity_nsgf_home_video, BR.vm, mStates)
                .addBindingParam(BR.adapterVideo, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityNsgfHomeVideoBinding) getBinding();
        mBinding.titlebar.titleBarMenu.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarMenu.setImageResource(R.drawable.ic_home_video_sort_true);
        mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_home_video_map);
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);

        mStates.titleBar.set("视频监控");

        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                mAccountRequester.videoNewList(UserInfo.getInstance().getProjectCode(), "");

            }
        });
        mBinding.webView.getWebView().addJavascriptInterface(new WebViewInterface(), "android");

        getController().displayLoading();

        mAccountRequester.getReginVideoList().observe(this, listResponseStatus -> {
            getController().dismissLoading();
            if (listResponseStatus.getResponseCode() == 200) {

                mStates.list.set(listResponseStatus.getData());

                JSONArray initArray = new JSONArray();
                JSONObject params = null;
                for (VideoListBean dataBean : listResponseStatus.getData()) {
                    for (VideoListBean.ListBean lateAndEarlyListBean : dataBean.getList()) {

                        if (!StringUtil.isEmpty(lateAndEarlyListBean.getCoordinates())) {

                            String[] points = lateAndEarlyListBean.getCoordinates().split(",");
                            if (points.length == 2) {

                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("callingMode", lateAndEarlyListBean.getCallingMode());
                                jsonObject.put("deviceCode", lateAndEarlyListBean.getDeviceCode());
                                jsonObject.put("channelId", lateAndEarlyListBean.getChannelId());
                                jsonObject.put("lat", points[1]);
                                jsonObject.put("lon", points[0]);
                                jsonObject.put("positionName", lateAndEarlyListBean.getDeviceName());
                                jsonObject.put("deviceName", lateAndEarlyListBean.getDeviceName());
                                jsonObject.put("status", 5);
                                initArray.add(jsonObject);
                                if (null == params)
                                    params = jsonObject;
                            }
                        }
                    }
                }

                callJavaScriptDrawInitPintFunction(params, initArray);
            }
        });

    }

    private void callJavaScriptDrawInitPintFunction(JSONObject object, JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("zoomToPointProject(" + object + "," + "'" + list + "'" + ");", null);

    }

    public static class CheckWorkAttendanceState extends StateHolder {

        public final State<String> name = new State<>("123123");

        public final State<String> password = new State<>("123123");

        public final State<List<VideoListBean>> list = new State<>(new ArrayList<>());

        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<Integer> mWayMap = new State<>(View.GONE);
        public final State<Integer> mWayList = new State<>(View.VISIBLE);
        public final State<String> searchContent = new State<>("");

    }

    private boolean mapList = true;//false 地图 true 列表

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        int id = v.getId();
        if (id == R.id.title_bar_menu) {
            mBinding.titlebar.titleBarMenu.setImageResource(R.drawable.ic_home_video_sort_true);
            mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_home_video_map);
            mBinding.webView.setVisibility(View.GONE);
            mBinding.recyclerViewLate.setVisibility(View.VISIBLE);
            mapList = true;
        } else if (id == R.id.title_bar_clear) {
            mBinding.titlebar.titleBarMenu.setImageResource(R.drawable.ic_home_video_sort);
            mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_home_video_map_true);
            mBinding.webView.setVisibility(View.VISIBLE);
            mBinding.recyclerViewLate.setVisibility(View.GONE);
            mapList = false;
        }
        if (mapList) {
            mStates.mWayList.set(View.VISIBLE);
            mStates.mWayMap.set(View.GONE);
        } else {
            mStates.mWayList.set(View.GONE);
            mStates.mWayMap.set(View.VISIBLE);
        }
    }

    public class ClickProxy {

        public void search() {
            mAccountRequester.videoNewList(UserInfo.getInstance().getProjectCode(), mStates.searchContent.get());
        }
    }


    /**
     * Js调用的JavascriptInterface
     */
    public class WebViewInterface {

        @JavascriptInterface
        public void openDetails(String src) {
            Gson gson = new Gson();
            ClockInBean.DataBean.LateAndEarlyListBean info = gson.fromJson(src, ClockInBean.DataBean.LateAndEarlyListBean.class);

            startActivity(new Intent()
                    .putExtra("callingMode", info.getCallingMode())
                    .putExtra("deviceCode", info.getDeviceCode())
                    .putExtra("channelId", info.getChannelId())
                    .putExtra("deviceName", info.getDeviceName())
                    .putExtra("lat", info.getLat())
                    .putExtra("lon", info.getLon())
                    .setClass(VideoListActivity.this,
                            VideoInfoActivity.class));
        }
    }

}
